<script setup lang="ts">
import {
  addPatientApi,
  getPatientDetailApi,
  updatePatientApi,
} from "@/apis/patient"
import { ref } from "vue"

// 1. 表单数据
const formData = ref({
  // 患者姓名
  name: "",
  // 患者身份证号
  idCard: "",
  // 患者性别 1：男，0：女
  gender: 1,
  // 是否为默认患者 1：是，0：否
  defaultFlag: 1,
})

// 是否为默认就诊人
const onSwitchChange = (event: UniHelper.SwitchOnChangeEvent) => {
  // switch 组件收集的是 boolean 类型，后端需要的是数字 0 或 1
  formData.value.defaultFlag = event.detail.value ? 1 : 0
}
// 2. 表单实例
const formRef = ref<UniHelper.UniFormsInstance>()

// 3. 校验规则
const formRules: UniHelper.UniFormsRules = {
  name: {
    rules: [
      { required: true, errorMessage: "请输入患者姓名" },
      {
        // ^[\u4e00-\u9fa5]{2,5}$
        pattern:
          /^([^\x00-\xff]{2,7}|[^\x00-\xff]{2}·[^\x00-\xff]{1,5}|[^\x00-\xff]{1,2}·[^\x00-\xff]{2,7})$/,
        errorMessage: "请输入正确的姓名",
      },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: "请输入身份证号" },
      {
        //  '^[1-9]\\d{5}(?:18|19|20)\\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\\d|30|31)\\d{3}[\\dXx]$'
        pattern:
          /^(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|([1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3})$/,
        errorMessage: "请输入正确的身份证号",
      },
    ],
  },
  // 身份证第 17 位表示性别，奇数表示男性 1，偶数表示女性 0。
  gender: {
    rules: [
      { required: true, errorMessage: "请选择性别" },
      {
        // 自定义校验规则
        validateFunction: (rule, value, data, callback) => {
          // 判断身份证第 17 位(索引为16)是否与选择的性别一致
          if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
            // callback 处理提示错误信息
            callback("身份证号与性别不匹配")
          }
          // 验证通过返回 true
          return true
        },
      },
    ],
  },
}

// 4. 提交表单
const onSubmit = async () => {
  try {
    // 校验表单
    await formRef.value?.validate?.()
    // 判断是否有id
    if (pageParams.id) {
      // 修改患者信息
      await updatePatientApi({
        ...formData.value,
        id: pageParams.id,
      })
    } else {
      // 添加患者
      await addPatientApi(formData.value)
    }
    // 成功提示
    uni.showToast({ title: "保存成功", icon: "success" })
    // 跳转上一页
    uni.navigateBack()
  } catch (error) {
    console.log(error)
  }
}

/**
 * defineProps
 *  页面 - 获取页面参数
 *  组件 - 获取父传子的参数
 */
const pageParams = defineProps<{ id: string }>()
const getDetail = async () => {
  const res = await getPatientDetailApi(pageParams.id)
  formData.value = {
    name: res.name,
    idCard: res.idCard,
    gender: res.gender || 0,
    defaultFlag: res.defaultFlag,
  }
}

if (pageParams.id) {
  uni.setNavigationBarTitle({ title: "编辑患者" })
  getDetail()
}
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms
        border
        label-width="220rpx"
        ref="formRef"
        v-model="formData"
        :rules="formRules"
      >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              :checked="formData.defaultFlag === 1"
              color="#20c6b2"
              style="transform: scale(0.7)"
              @change="onSwitchChange"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
